package com.appkubes.mall.restful.application.user.account.withdraw.service.impl;

import com.appkubes.mall.core.common.constants.MallUserAccountWithdrawConstants;
import com.appkubes.mall.core.entity.MallUserAccount;
import com.appkubes.mall.core.entity.MallUserAccountWithdraw;
import com.appkubes.mall.core.service.impl.BaseMallUserAccountWithdrawServiceImpl;
import com.appkubes.mall.restful.application.user.account.account.entity.vo.WithDrawVO;
import com.appkubes.mall.restful.application.user.account.account.service.UserAccountService;
import com.appkubes.mall.restful.application.user.account.withdraw.service.AccountWithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@Service
@Slf4j
public class AccountWithdrawServiceImpl extends BaseMallUserAccountWithdrawServiceImpl implements AccountWithdrawService {
    @Resource
    UserAccountService accountService;

    @Override
    public Boolean addWithdrawLog(WithDrawVO withDrawVO) {
        log.info("addWithdrawLog: {}", withDrawVO);
        MallUserAccount account = accountService.getById(withDrawVO.getUserKey());
        log.info("addWithdrawLog account: {}", account);
        if (account.getTotalBrokerage().compareTo(withDrawVO.getWithdrawMoney()) < 0) {
            return false;
        }
        Boolean ret = accountService.addBrokerage(withDrawVO.getUserKey(), withDrawVO.getWithdrawMoney().multiply(BigDecimal.valueOf(-1)));

        if (ret) {
            //提交申请,等待审核
            log.info("addWithdrawLog addBrokerage : {}", ret);
            MallUserAccountWithdraw mallUserAccountWithdraw = new MallUserAccountWithdraw();
            BeanUtils.copyProperties(withDrawVO, mallUserAccountWithdraw);
            mallUserAccountWithdraw.setSourceType(MallUserAccountWithdrawConstants.SourceType.ACCOUNT.name());
            mallUserAccountWithdraw.setState(MallUserAccountWithdrawConstants.State.UNPROCESSED.name());
            mallUserAccountWithdraw.setCreateTime(new Date());
            mallUserAccountWithdraw.setUpdateTime(new Date());
            mallUserAccountWithdraw.setAppKey(null);
            this.save(mallUserAccountWithdraw);
        }
        return ret;
    }
}
